<template>
  <el-upload
    v-model:file-list="fileList"
    action="#"
    :limit="field.limit"
    :on-exceed="handleExceed"
    :accept="acceptType"
    :http-request="httpRequest"
  >
    <el-button type="primary">点击上传</el-button>
  </el-upload>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import {
  ElMessage,
  type UploadProps,
  type UploadRequestOptions,
  type UploadUserFile
} from "element-plus";
import { FormField } from "../utils";

interface Props {
  modelValue: string[];
  field: FormField;
}

interface Emits {
  (e: "update:modelValue", value: string[]): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const fileList = ref<UploadUserFile[]>([]);

const acceptType = computed(() => {
  return props.field.fileType ? props.field.fileType.join(",") : "";
});

const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is ${props.field.limit}, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  );
};

const httpRequest = (options: UploadRequestOptions) => {
  // 实现文件上传逻辑
  emit("update:modelValue", [
    ...fileList.value.map(el => el.url),
    URL.createObjectURL(options.file)
  ]);
  return Promise.resolve();
};
</script>
